package com.vast.admin.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.api.BestsignOpenApi;
import com.vast.admin.api.entity.RegUser;
import com.vast.admin.api.response.AsynTaskResponse;
import com.vast.admin.api.response.BestsignResponse;
import com.vast.admin.entity.*;
import com.vast.admin.entity.enums.OperatorEum;
import com.vast.admin.entity.enums.QueryOrderEnum;
import com.vast.admin.mapper.CompanyMapper;
import com.vast.admin.service.CompanyPaymentTypeService;
import com.vast.admin.utils.QueryBuilder;
import com.vast.admin.utils.TableFieldColumnsUtils;
import com.vast.common.core.domain.entity.SysDept;
import com.vast.common.core.domain.entity.SysRole;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.common.utils.StringUtils;
import com.vast.system.domain.SysUserRole;
import com.vast.system.exception.BusinessException;
import com.vast.system.service.ISysDeptService;
import com.vast.system.service.ISysRoleService;
import com.vast.system.service.ISysUserRoleService;
import com.vast.system.service.ISysUserService;
import com.vast.system.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class CompanyService extends ServiceImpl<CompanyMapper, Company> {

    @Autowired
    private BestsignOpenApi bestsignOpenApi;

    @Autowired
    private CompanyAccountService companyAccountService;

    @Autowired
    private DealRecordService dealRecordService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService managerService;

    @Autowired
    private ISysUserRoleService managerRoleService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private CompanyPaymentTypeService companyPaymentTypeService;


    public IPage<Company> queryList(SysUser manager, Page<Company> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        Map<String, String> fieldColumns = TableFieldColumnsUtils.getInstance().getFieldTableColumns(Company.class);
        if (listMode) {
            // size 小于 0 不在查询 total 及分页，自动调整为列表模式。
            // 注意！！这个地方自己控制好！！
            page.setSize(-1);
        }
        if (!StringUtils.isEmpty(queryItems)) {
            List<QueryBuilder> queryBuilders = new ArrayList<>();
            String[] queryItemArr = queryItems.split(";");
            if(queryItemArr.length > 0){
                for (String queryItemStr : queryItemArr) {
                    String[] itemArr = queryItemStr.split(",");
                    if(itemArr.length == 3){
                        String as = itemArr[1];
                        String params = itemArr[2];
                        if(!StringUtils.isEmpty(params)){
                            queryBuilders.add(new QueryBuilder(itemArr[0], OperatorEum.valueOf(as),itemArr[2]));
                        }
                    }
                }
            }

            for (QueryBuilder queryBuilder : queryBuilders) {
                //查询字段
                String field = queryBuilder.getField();
                //查询参数值
                String params = queryBuilder.getParams();
                if (fieldColumns.containsKey(field) && !StringUtils.isEmpty(params)) {
                    //表属性
                    String tableColumn = fieldColumns.get(field);
                    if (queryBuilder.getAs() == OperatorEum.EQ) {
                        queryWrapper.eq(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.LIKE){
                        queryWrapper.like(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.LIKELEFT){
                        queryWrapper.likeLeft(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.LIKERIGHT){
                        queryWrapper.likeRight(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.GE){
                        queryWrapper.ge(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.LE){
                        queryWrapper.le(tableColumn, params);
                    }
                }
            }
        }

        if(!manager.isHasRole(Constant.SUPER_ADMIN)){//超级管理员
            QueryWrapper<SysUserRole> managerRoleQueryWrapper = new QueryWrapper<>();
            managerRoleQueryWrapper.eq(SysUserRole.COL_MANAGER_ID, manager.getUserId());
            List<SysUserRole> managerRoles = managerRoleService.list(managerRoleQueryWrapper);
            boolean isCompanyAdmin = false;
            boolean isSystemManager = false;
            if(managerRoles!= null && !managerRoles.isEmpty()){
                List<Long> roleIds = new ArrayList<>();
                for (SysUserRole managerRole : managerRoles) {
                    roleIds.add(managerRole.getRoleId());
                }
                List<SysRole> roleList = (List<SysRole>) roleService.listByIds(roleIds);
                if(roleList!= null && !roleList.isEmpty()){
                    for (SysRole role : roleList) {
                        if(Constant.COMPANY_ADMIN_ALIAS.equals(role.getRoleKey())){//如果是企业管理员
                            isCompanyAdmin = true;
                        }else if(Constant.SYSTEM_MANAGER_ALIAS.equals(role.getRoleKey())){ //系统管理员
                            isSystemManager = true;
                        }
                    }
                }
            }
            if(isSystemManager){

            }else{
                if(isCompanyAdmin){
                    queryWrapper.eq(Company.COL_COMPANY_ID, manager.getCompanyId());
                }else{
                    queryWrapper.eq(Company.COL_CREATE_BY, manager.getUserId());
                }
            }
        }


        if (!StringUtils.isEmpty(orderField)) {
            String[] orderByColumns = orderField.split(",");
            String queryOrderByColumns = "";
            if (orderByColumns.length > 0) {
                StringBuilder sb = new StringBuilder();
                for (String orderByColumn : orderByColumns) {
                    if (fieldColumns.containsKey(orderByColumn)) {
                        sb.append(fieldColumns.get(orderByColumn)).append(",");
                    }
                }
                if (sb.length() > 0) {
                    queryOrderByColumns = sb.deleteCharAt(sb.length() - 1).toString();
                }
            }
            if (!StringUtils.isEmpty(queryOrderByColumns)) {
                if(order == null){
                    order = QueryOrderEnum.ASC;
                }
                if (order == QueryOrderEnum.ASC) {
                    queryWrapper.orderByAsc(queryOrderByColumns);
                } else if (order == QueryOrderEnum.DESC) {
                    queryWrapper.orderByDesc(queryOrderByColumns);
                }
            }
        }



        IPage<Company> result = baseMapper.selectPage(page, queryWrapper);
        for (Company record : result.getRecords()) {
            SysUser creator = managerService.getById(record.getCreateBy());
            if(creator != null){
                record.setCreator(creator.getNickName());
            }
        }
        return result;
    }

    @Transactional
    public boolean addOrUpdate(SysUser manager, Company bean) {
        if (bean.getPaymentType() == 2) {
            if (bean.getCompanyPaymentTypes() == null || bean.getCompanyPaymentTypes().isEmpty()) {
                throw new BusinessException("按合同金额区间收费详情为空");
            }
        }
        boolean result = false;
        if (bean.getId() == null) {
            List<Company> companyList = baseMapper.selectList(new QueryWrapper<Company>().eq(Company.COL_CONTACT_MOBILE,bean.getContactMobile()));
            if(companyList == null || companyList.isEmpty()){ //判断该企业是否已存在
                bean.setCreateBy(manager.getUserId());
                bean.setUpdateBy(manager.getUserId());
                bean.setCreateTime(DateTime.now());
                bean.setUpdateTime(DateTime.now());
                bean.setCompanyId(manager.getCompanyId());
                bean.setValid(1);
                bean.setBestsignAccount(UUID.randomUUID().toString());
                //注册上上签用户
                regBestsignUser(bean);

                baseMapper.insert(bean);

                //创建账户
                createCompanyAccount(manager,bean);

                //创建企业部门
                createCompanyDept(manager,bean);
                result = true;
            }else{
                //该企业已添加
                return false;
            }
        } else {
            bean.setUpdateBy(manager.getUserId());
            bean.setUpdateTime(DateTime.now());
            bean.setValid(1);
            baseMapper.updateById(bean);
            result = true;

        }
        if (result) {
            if (bean.getPaymentType() == 2) {
                companyPaymentTypeService.saveCompanyPaymentTypes(bean.getId(), bean.getCompanyPaymentTypes());
            }
        }
        return result;
    }

    public Company info(SysUser manager, Long id) {
        Company bean = baseMapper.selectById(id);
        bean.setCompanyPaymentTypes(companyPaymentTypeService.getByCompanyId(bean.getId()));
        return bean;
    }


    public boolean delete(SysUser manager, Long[] ids) {

        List<Long> idsList = java.util.Arrays.asList(ids);
        int count = baseMapper.deleteBatchIds(idsList);

        return count == ids.length;

    }


    /**
     * 创建企业部门
     * @param company
     */
    private void createCompanyDept(SysUser manager,Company company){
		SysDept dept = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.COL_DEPT_NAME,company.getName()));
        if(dept == null){
			SysDept parentDept = deptService.getById(manager.getDeptId());
			SysDept bean = new SysDept();
            if(parentDept != null){
                bean.setParentId(parentDept.getDeptId());
                bean.setParentName(parentDept.getDeptName());
                bean.setAncestors(parentDept.getAncestors()+parentDept.getDeptId()+",");
            }
            bean.setOrderNum("1");
            bean.setStatus("1");
//            bean.setType(1);
            bean.setCompanyId(company.getId());
            bean.setDeptName(company.getName());
            bean.setCreateBy(manager.getUserId());
            bean.setUpdateBy(manager.getUserId());
            bean.setCreateTime(DateTime.now());
            bean.setUpdateTime(DateTime.now());
            bean.setValid("1");
            deptService.save(bean);
        }
    }

    /**
     * 创建企业账户
     * @param company
     */
    private void createCompanyAccount(SysUser manager,Company company){
        CompanyAccount companyAccount = companyAccountService.getOne(new QueryWrapper<CompanyAccount>().eq(CompanyAccount.COL_COMPANY_ID, company.getId()));
        if(companyAccount == null) { //账户不存在, 新建账户
            //添加操作记录
            DealRecord dealRecord = new DealRecord();
            dealRecord.setCreateBy(manager.getUserId());
            dealRecord.setUpdateBy(manager.getUserId());
            dealRecord.setCreateTime(DateTime.now());
            dealRecord.setUpdateTime(DateTime.now());
            dealRecord.setValid(1);
            dealRecord.setAccountId(company.getId());
            dealRecord.setOperation(1);
            dealRecord.setPaymentType(1);
            dealRecord.setRemark("创建账户");
            dealRecord.setOriginalAmount(BigDecimal.ZERO);
            dealRecord.setRechargeAmount(BigDecimal.ZERO);
            dealRecord.setExtraAmount(BigDecimal.ZERO);
            dealRecordService.save(dealRecord);

            CompanyAccount bean = new CompanyAccount();
            bean.setCreateBy(manager.getUserId());
            bean.setUpdateBy(manager.getUserId());
            bean.setCreateTime(DateTime.now());
            bean.setUpdateTime(DateTime.now());
            bean.setMoney(BigDecimal.ZERO);
            bean.setLegalPerson(company.getLegalPerson());
            bean.setContactMobile(company.getLegalPersonMobile());
            bean.setCompanyName(company.getName());
            bean.setCompanyId(company.getId());
            bean.setStatus(1);
            bean.setValid(1);
            //添加
            companyAccountService.save(bean);
        }
    }

    /**
     * 注册上上签用户
     * @param company
     */
    private void regBestsignUser(Company company) {
        RegUser regUser = new RegUser();
        regUser.setAccount(company.getBestsignAccount());
        regUser.setName(company.getName());
        regUser.setUserType("2");
        regUser.setApplyCert("1");
        regUser.initCredential();
        regUser.getCredential().setContactMobile(company.getLegalPersonMobile());
        regUser.getCredential().setIdentity(company.getLegalPersonIdentity());
        regUser.getCredential().setLegalPerson(company.getLegalPerson());
        regUser.getCredential().setLegalPersonIdentity(company.getLegalPersonIdentity());
        regUser.getCredential().setOrgCode(company.getRegCode());
        regUser.getCredential().setRegCode(company.getRegCode());
        regUser.getCredential().setTaxCode(company.getRegCode());
//        BeanUtils.copyProperties(company, regUser.getCredential());
        BestsignResponse<AsynTaskResponse> bestsignResponse = bestsignOpenApi.companyReg(regUser);
        company.setBestsignTaskId(bestsignResponse.getData().getTaskId());
        company.setBestsignTokenStatus(0);
//        byte[] bytes = bestsignOpenApi.downloadSignatureImage(company.getBestsignAccount(), "default");
//        String signaturePath =  FileUtils.saveFile(bytes, System.currentTimeMillis() + ".png", FileUtils.FileType.SIGNATURE);
//        company.setSignaturePath(signaturePath);
    }

    /**
     * 获取公司信息
     * @param bestsignAccount
     * @param taskId
     * @return
     */
    public Company getByBestsignAccount(String bestsignAccount, String taskId) {
        QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
        companyQueryWrapper.eq(Company.COL_BESTSIGN_ACCOUNT, bestsignAccount);
        if (org.springframework.util.StringUtils.hasText(taskId)) {
            companyQueryWrapper.eq(Company.COL_BESTSIGN_TASK_ID, taskId);
        }
        return super.getOne(companyQueryWrapper);
    }

    /**
     * 通过手机号码查询公司信息
     * @param phone 法人或经办人手机号码
     * @return
     */
    public Company getCompanyByPhone(String phone) {
        QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
        companyQueryWrapper.eq(Company.COL_CONTACT_MOBILE,phone);
        return getOne(companyQueryWrapper);
    }

    public List<Company> selectCompanyList(Company company) {
        return null;
    }


    public List<Company> getMineOfCompanyList(SysUser manager,Company company) {
       return baseMapper.getMineOfCompanyList(manager,company);
    }
}
